import React, { useEffect, useState, useRef } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import ProjectPlan from './ProjectPlan';
import BillInfo from './BillInfo';
import SettlementInfo from './SettlementInfo';
import { Button, Divider, Form, FormInstance, Popconfirm } from 'antd';
import ProForm, { ProFormText } from '@ant-design/pro-form';
import { 
  getPlanOrderDetail, 
  getDischargeStatus,
  handleDischarge,
  getPlanOrderList,
  getPatientHospitalizationInfo } from '@/services/order/api';
import { MsgType, showMsg, isNull } from '@/utils/utils';
import { PlanOrderStatus } from '@/utils/constants';
import { history, useModel } from 'umi';
import './style.less';
import BreadcrumbDept from '@/components/BreadcrumbDept';
import PermissionControl from '@/components/PermissionControl';
import ChoicePatient from '@/components/ChoicePatient';

interface DetailProps {
  location?: any;
  type?: string;
}
const PlanOrderDetail: React.FC<DetailProps> = (props) => {
  const { location } = props;
  const { query } = location;
  const { order_id, eventNo } = query;
  const [detail, setDetail] = useState<any>({});
  const [orderid, setOrderid] = useState(order_id);

  const formRef = useRef<FormInstance>();
  const billRef = useRef(); // 获取账单信息的实例
  const settRef = useRef(); // 获取结算信息的实例
  const planRef = useRef();
  const patientRef = useRef(); // 获得患者信息的实例
  const { initialState } = useModel('@@initialState');

  const [admissionNum, setAdmissionNum] = useState<string>('');
  const [patientHospitalInfo, setPatientHospitalInfo] = useState<ORDERAPI.PatientHospitalInfo>({} as ORDERAPI.PatientHospitalInfo);
 
  // 出院状态
  const [dischargeStauts, setDischargeStatus] = useState<string>('');

  // 是否有计划订单
  const [hasPlan, setHasPlan] = useState<boolean>(false);

  // 计划订单详情
  const fetchPlanOrderDetail = (id?: string, flag) => {
    getPlanOrderDetail(id || orderid || order_id).then(data => {
      setDetail(data);

      const patinfo = {
        ...data,
        patient_name: data.patient_name,
        patient_id: data.patient_id,
        patient_age: data.patient_age,
        admission_num: data.admission_num || admissionNum,
        bed_no: data.bed_no,
        dept_name: data.create_dept_name,
        admission_dept_name: data.patient_dept_name,
        admission_dept_code: data.patient_dept_code
      };
      // 默认为false,为false的时候重新给患者信息赋值，由于点了更换患者，查询患者的时候信息多，查询计划详情的时候信息少，造成乱跳现象，故这么做
      if (!flag) {
        setPatientHospitalInfo(patinfo as ORDERAPI.PatientHospitalInfo);
        patientRef.current?.update(patinfo);
      }
      setAdmissionNum(data.admission_num);
      getDischargeStatus({
        patient_id: data.patient_id,
        admission_num: data.admission_num
      }).then(data => {
        setDischargeStatus(data.manager_status);
      });
    }).catch(err => {
      showMsg(err?.data?.errmsg);
    });
  }

  const [loading, setLoading] = useState<boolean>(false);
  const [visible, setVisible] = useState<boolean>(false);

  useEffect(() => {
    if (!isNull(order_id)) {
      fetchPlanOrderDetail();
    } else if (!isNull(eventNo)) { // 单点登录来的住院号，则查询用户信息
      patientRef.current.fetch?.(eventNo)
    }
    setOrderid(order_id)
  }, [order_id]);

  console.log('orderid', order_id, orderid)
  return (
    <PageContainer title="查看编辑(计划订单)" extra={[
      <BreadcrumbDept />
     ]} className="plan-detail-container" breadcrumb={{}} onBack={() => history.push({
       pathname: '/order/planOrder',
       query: {
         from: 'detail',
         order_id,
       }
     })}>
      <div className="service-record">
        <div className="header">
            <div className="title">1.住院患者信息</div>
            <div className="btns">
              {
                (detail.plan_status === 'S') && <PermissionControl action_id="400401022">
                  <Popconfirm
                    visible={visible}
                    placement="bottomRight"
                    title={<div>办理出院后无法再次为该患者创建执行计划，<br/>是否确认出院？</div>}
                    onCancel={() => setVisible(false)}
                    okButtonProps={{
                      loading
                    }}
                    onConfirm={async () => {
                      try {
                        setLoading(true);
                        await handleDischarge(orderid);
                        showMsg('办理出院成功', MsgType.SUCCESS);
                        setLoading(false);
                        setVisible(false);
                        fetchPlanOrderDetail();
                        planRef?.current?.reload();
                        billRef?.current?.reload(); 
                        settRef?.current?.reload();
                      } catch (error) {
                        showMsg(error?.data?.errmsg);
                        setLoading(false);
                      }
                    }}
                  >
                    <Button 
                      disabled={dischargeStauts !== 'U'}
                      style={{marginRight: 10}} 
                      onClick={() => {
                        setVisible(true);
                      }}
                      type="primary">
                        办理出院
                    </Button>
                  </Popconfirm>
                </PermissionControl>
              }
              计划状态：
              <span style={{color: '#52C41A'}}>
                {detail.plan_status ? PlanOrderStatus[detail.plan_status] : '待创建'}
              </span>
            </div>
          </div>
          <Divider style={{margin: '10px 0'}}/>
          <ChoicePatient
            ref={patientRef}
            type='zy'
            fromTo='planOrder'
            showMore={false}
            onChoice={async(info, data) => {
              if (!isNull(info.patient_id)) {
                setPatientHospitalInfo(Object.assign({}, info, {admission_num: info.visit_no}));
                
                if (data.have_plan === 'Y') {
                  const res: ORDERAPI.PlanOrderItemList = await getPlanOrderList({
                    current: 1,
                    pageSize: 20,
                    admission_num: info.visit_no
                  });
                  const item = res.record_list?.shift();
                  console.log(item);
                  if (item) {
                    setOrderid(item.order_id);
                    fetchPlanOrderDetail(item.order_id, true);
                  } 
                } else {
                  setOrderid('');
                  setDetail({});
                  billRef.current.reload();
                  planRef.current.reload();
                  settRef.current.reload();
                }
                setDischargeStatus(data.manager_status);
                setHasPlan(data.have_plan === 'Y');
              } else {
                showMsg('未找到患者信息', MsgType.INFO);
                setPatientHospitalInfo({});
                setDetail({});
                setOrderid('');
                billRef.current.reload();
                planRef.current.reload();
                settRef.current.reload();
              }
            }}
            changePatient={() => {
              setPatientHospitalInfo({});
              setDetail({});
              setAdmissionNum('');
              setOrderid('');
              patientRef?.current?.clear();
              planRef?.current?.clear();
              billRef?.current?.clear();
              settRef?.current?.clear();
              formRef.current?.setFieldsValue({ admission_num: null })
              history.replace('/order/planOrder/detail?type=add');
            }}
          />
      </div>
      
      <ProjectPlan 
        ref={planRef}
        startProject={() => {
          billRef?.current?.reload(); 
          settRef?.current?.reload();
        }} 
        stopProject={() => {
          billRef?.current?.reload(); 
          settRef?.current?.reload();
        }}
        order_id={orderid} 
        detail={detail}
        dischargeStatus={dischargeStauts}
        hasPlan={hasPlan}
        patientHospitalInfo={patientHospitalInfo} />

      <BillInfo
        ref={billRef}
        dischargeStatus={dischargeStauts}
        order_id={orderid} 
        reload={() => {
          planRef.current.reload();
          settRef.current.reload();
          fetchPlanOrderDetail();
        }}
        detail={detail} />
      
      <SettlementInfo
        ref={settRef}
        dischargeStatus={dischargeStauts}
        order_id={orderid} 
        cancelSettle={() => {
          billRef?.current?.reload(); 
          fetchPlanOrderDetail();
        }}
        onRefresh={() => {
          planRef?.current?.reload();
          billRef?.current?.reload(); 
          settRef?.current?.reload();
        }}
        reload={() => {
          billRef?.current?.reload(); 
          fetchPlanOrderDetail();
        }}
      />
      
    </PageContainer>
  );
};
export default PlanOrderDetail;
